package org.chen.ctrip.service.translate.markdown;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class HtmlToMarkdownService {

    /**
     * 将HTML表格转换为Markdown格式，并按天分割
     */
    public List<String> convertHtmlToMarkdownByDay(String html) {
        if (html == null || html.trim().isEmpty()) {
            return new ArrayList<>();
        }

        try {
            // 先进行HTML清理和预处理
            String cleanedHtml = preprocessHtml(html);

            // 按天分割HTML内容
            List<String> dayTables = splitByDay(cleanedHtml);

            // 将每天的HTML转换为Markdown
            List<String> markdownDays = new ArrayList<>();
            for (int i = 0; i < dayTables.size(); i++) {
                String dayHtml = dayTables.get(i);
                String dayMarkdown = convertSingleDayToMarkdown(dayHtml, i + 1);
                if (!dayMarkdown.trim().isEmpty()) {
                    markdownDays.add(dayMarkdown);
                }
            }

            return markdownDays;

        } catch (Exception e) {
            log.error("HTML转Markdown失败: {}", e.getMessage(), e);
            // 如果转换失败，返回纯文本版本
            List<String> fallback = new ArrayList<>();
            fallback.add(Jsoup.parse(html).text());
            return fallback;
        }
    }

    /**
     * 预处理HTML，去除不必要的标签和样式
     */
    private String preprocessHtml(String html) {
        Document doc = Jsoup.parse(html);

        // 移除所有style属性
        doc.select("*").removeAttr("style");

        // 移除不必要的CSS类名，只保留有语义的
        doc.select("*").forEach(element -> {
            String className = element.className();
            if (className.contains("print_table")) {
                // 保留表格相关的类名
                element.className();
            } else {
                element.removeAttr("class");
            }
        });

        // 移除不必要的标签但保留内容
        doc.select("div.bg-gray-100, div.flex, div.grid").unwrap();
        doc.select("span, i.icon_base").unwrap();

        // 移除图片但保留alt文本
        Elements images = doc.select("img");
        for (Element img : images) {
            String alt = img.attr("alt");
            if (!alt.isEmpty()) {
                img.replaceWith(new Element("span").text("[图片: " + alt + "]"));
            } else {
                img.remove();
            }
        }

        return doc.html();
    }

    /**
     * 按天分割HTML内容
     */
    private List<String> splitByDay(String html) {
        List<String> dayTables = new ArrayList<>();

        Document doc = Jsoup.parse(html);
        Elements tables = doc.select("table.print_table");

        for (Element table : tables) {
            // 查找Day标识
            Elements dayHeaders = table.select("th:contains(Day)");
            if (!dayHeaders.isEmpty()) {
                dayTables.add(table.outerHtml());
            }
        }

        // 如果没有找到Day标识，按表格分割
        if (dayTables.isEmpty()) {
            for (Element table : tables) {
                dayTables.add(table.outerHtml());
            }
        }

        return dayTables;
    }

    /**
     * 将单天的HTML转换为Markdown
     */
    private String convertSingleDayToMarkdown(String dayHtml, int dayNumber) {
        Document doc = Jsoup.parse(dayHtml);
        StringBuilder markdown = new StringBuilder();

        markdown.append("# Day ").append(dayNumber).append("\n\n");

        Element table = doc.selectFirst("table");
        if (table == null) {
            return "";
        }

        Elements rows = table.select("tr");

        for (Element row : rows) {
            // 处理Day标题行
            Elements dayHeaders = row.select("th:contains(Day)");
            if (!dayHeaders.isEmpty()) {
                Element titleTh = row.select("th").last();
                if (titleTh != null) {
                    markdown.append("**行程**: ").append(titleTh.text().trim()).append("\n\n");
                }
                continue;
            }

            // 处理普通行
            Elements cells = row.select("td");
            if (cells.size() >= 2) {
                Element timeCell = cells.get(0);
                Element contentCell = cells.get(1);

                String time = extractTime(timeCell);
                String title = extractTitle(contentCell);
                String content = extractContent(contentCell);
                String grayInfo = extractGrayInfo(contentCell);

                if (!time.isEmpty()) {
                    markdown.append("## ").append(time);
                    if (!title.isEmpty()) {
                        markdown.append(" - ").append(title);
                    }
                    markdown.append("\n\n");
                }

                if (!content.isEmpty()) {
                    markdown.append(content).append("\n\n");
                }

                if (!grayInfo.isEmpty()) {
                    markdown.append("*").append(grayInfo).append("*\n\n");
                }
            }
        }

        return markdown.toString();
    }

    /**
     * 提取时间信息
     */
    private String extractTime(Element timeCell) {
        String timeText = timeCell.select(".print_table_time").text().trim();
        return timeText.isEmpty() ? "" : timeText;
    }

    /**
     * 提取标题信息
     */
    private String extractTitle(Element contentCell) {
        Element titleElement = contentCell.selectFirst(".print_table_title");
        return titleElement != null ? titleElement.text().trim() : "";
    }

    /**
     * 提取主要内容
     */
    private String extractContent(Element contentCell) {
        StringBuilder content = new StringBuilder();

        // 提取景点信息
        Elements gradeBoxes = contentCell.select(".print_table_grade_box");
        for (Element gradeBox : gradeBoxes) {
            String spotName = gradeBox.text().replaceAll("\\d+\\.\\d+/\\d+", "").trim();
            if (spotName.contains("或")) {
                content.append("**选择**: ").append(spotName).append("\n");
            } else {
                content.append("**景点**: ").append(spotName).append("\n");
            }
        }

        // 提取描述文本
        Elements richContent = contentCell.select(".rich_content_view_20191129, .print_table_td_text");
        for (Element rich : richContent) {
            String text = rich.text().trim();
            if (!text.isEmpty() && !text.matches(".*参考价格.*|.*CNY.*|.*活动时长.*")) {
                // 清理文本，移除多余的空白
                text = text.replaceAll("\\s+", " ");
                content.append(text).append("\n");
            }
        }

        // 提取费用信息
        Elements actLists = contentCell.select(".daily_itinerary_act_list");
        if (!actLists.isEmpty()) {
            content.append("\n**费用参考**:\n");
            for (Element actList : actLists) {
                Elements titles = actList.select(".daily_itinerary_act_title");
                Elements subTitles = actList.select(".daily_itinerary_act_sub_title");
                Elements notes = actList.select(".daily_itinerary_act_note");

                for (int i = 0; i < titles.size(); i++) {
                    content.append("- ").append(titles.get(i).text());
                    if (i < subTitles.size()) {
                        content.append(": ").append(subTitles.get(i).text());
                    }
                    if (i < notes.size()) {
                        content.append(" (").append(notes.get(i).text()).append(")");
                    }
                    content.append("\n");
                }
            }
        }

        return content.toString();
    }

    /**
     * 提取灰色提示信息
     */
    private String extractGrayInfo(Element contentCell) {
        Elements grayElements = contentCell.select(".print_table_td_gray");
        StringBuilder grayInfo = new StringBuilder();

        for (Element gray : grayElements) {
            String text = gray.text().trim();
            if (!text.isEmpty()) {
                if (!grayInfo.isEmpty()) {
                    grayInfo.append(" | ");
                }
                grayInfo.append(text);
            }
        }

        return grayInfo.toString();
    }

    /**
     * 兼容原有方法 - 简单的HTML表格转Markdown
     */
    public String convertHtmlTableToMarkdown(String html) {
        List<String> dayMarkdowns = convertHtmlToMarkdownByDay(html);
        return String.join("\n\n---\n\n", dayMarkdowns);
    }
}